package com.block.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.security.service.AppSignMannerService;
import com.block.common.security.service.factory.SignFactory;
import com.block.common.util.HttpReturnUtil;
import com.block.db.entity.AppEncrypt;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

public class SignInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        AppEncrypt appEncrypt=(AppEncrypt) request.getAttribute("appEncrypt");

        JSONObject oriData=(JSONObject) request.getAttribute("oriData");
        AppSignMannerService appSignMannerService = SignFactory.getAppSignManner(appEncrypt.getSignType());

        Date date= (Date) request.getAttribute("startDate");
        String uri= (String) request.getAttribute("uri");
        JSONObject transData = (JSONObject) request.getAttribute("tranData");

        Map<String,Object> reqMap= JSON.toJavaObject(transData,Map.class);
        boolean verify = appSignMannerService.validateSign(appEncrypt,null,reqMap,"",oriData);

        if (!verify){
            // 验签失败
            HttpReturnUtil.returnJson(response,appEncrypt, AppRspCodeConstant.CHECK_SIGN_ERROR,null,date,uri);
            return false;
        }
        return true;
    }

}
